package org.dashboard.utils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;

class DbPoolConnection {

    private static DbPoolConnection databasePool = null;

    private static HashMap<String, DruidDataSource> druidDataSources = null;

    private DbPoolConnection() {
        druidDataSources = new HashMap<>();
    }

    static synchronized DbPoolConnection getInstance() {
        if (null == databasePool) {
            databasePool = new DbPoolConnection();
        }
        return databasePool;
    }

    synchronized DruidDataSource getDataSource(Properties env) throws SQLException {
        String key = getPropertiesKey(env);
        DruidDataSource dataSource;
        if (druidDataSources.containsKey(key)) {
            dataSource = druidDataSources.get(key);
        } else {
            dataSource = new DruidDataSource();
            dataSource.setUrl(env.getProperty("url"));//连接字符串
            dataSource.setUsername(env.getProperty("username"));//用户名
            dataSource.setPassword(env.getProperty("password"));//密码
            dataSource.setDriverClassName(env.getProperty("driver"));//数据源驱动
            dataSource.setInitialSize(2);//初始化时建立物理连接的个数
            dataSource.setMaxActive(20);//最大连接池数量
            dataSource.setMinIdle(0);//最小连接池数量
            dataSource.setMaxWait(60000);//获取连接时最大等待时间，单位毫秒。
            dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
            dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
            dataSource.setTestWhileIdle(true);//建议配置为true，不影响性能，并且保证安全性。
            dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement，也就是PSCache
            dataSource.setBreakAfterAcquireFailure(true);//禁止重试
            druidDataSources.put(key, dataSource);
        }
        return dataSource;
    }

    private String getPropertiesKey(Properties env) {
        return env.getProperty("url")
                + env.getProperty("username")
                + env.getProperty("password")
                + env.getProperty("driver");
    }

}
